
Ext.define('FrontSuite.view.AppToolbar', {
    id:             'app-toolbar',
    extend:         'Ext.toolbar.Toolbar',  // defines the superclass. results in class inheritance.
    alias:          'widget.apptoolbar',    // creates an xtype: 'apptoolbar'
    enableOverflow: true,                   // enables a toolbar to overflow if it has too many tools to fit in the width provided

    db_name:   null,
    table_name:      null,

    newDatabaseDialog:      null,
    newDatabaseTableDialog: null,

    constructor: function (id) {
        var toolbar = this;
        if (id) {
            this.id = id;
        }

//console.log('AppToolbar.constructor()');
//console.log(FrontSuite.session);
        var user_token = FrontSuite.session.user_token;
        var loggedIn        = (user_token && user_token !== 'guest') ? true : false;
        var userButtonText  = (user_token) ? 'User ('+user_token+')' : 'User (guest)';

        var authdata = FrontSuite.session.authdata;

        var groupMenu = [];
        var group_id  = FrontSuite.session.group_id || 0;
        var groupButtonText = 'Group (none)';
        if (authdata && authdata.groups && authdata.groups.length > 0) {
            var groups   = authdata.groups;
            var i;
            for (i = 0; i < groups.length; i++) {
                groupMenu[i] = { text: groups[i].group_name, iconCls: 'icon-group', handler: function (btn, event) { toolbar.newGroup(btn.text); } };
                if (groups[i].group_id == group_id) groupButtonText = 'Group ('+groups[i].group_name+')';
            }
        }

        var appMenu = [];
        var app_id  = FrontSuite.session.app_id || 0;
        var appButtonText = 'Application (none)';
        if (authdata && authdata.apps && authdata.apps.length > 0) {
            var apps   = authdata.apps;
            var i;
            for (i = 0; i < apps.length; i++) {
                appMenu[i] = { text: apps[i].app_cd, iconCls: 'icon-application-side-tree', handler: function (btn, event) { toolbar.newApp(btn.text); } };
                if (apps[i].app_id == app_id) appButtonText = 'Application ('+apps[i].app_cd+')';
            }
        }

        this.items = [
            {
                xtype: 'label',
                html: '<img src="resources/images/logo_38x44.png" width="16" height="17">&nbsp;' + FrontSuite.options['app.title'],
                margins : '0 10 0 10',
                style: {
                    'font-size': '18px',
                    'font-weight': 'bold',
                    'font-style': 'italic'
                }
            },
            '-',
            {
                xtype: 'button',
                text: 'Favorites',
                iconCls: 'icon-application-cascade',
                menu: [
                    { text: 'Sample Dashboard', iconCls: 'icon-application', handler: function (btn) { FrontSuite.app.addTab('SampleDashboard'); } }
                    // '-',
                    // { text: 'Add Favorite View',    handler: function (btn) { FrontSuite.app.notify(btn.text); } }
                ]
            },
            '-',
            {
                id:   'app-toolbar-database',
                text: 'Database',
                iconCls: 'icon-server-database',
                menu: [
                    {
                      id:   'app-toolbar-database-select',
                      text: 'Choose Database',
                      iconCls: 'icon-server-go',
                      menu: [
                        { text: '(none)', iconCls: 'icon-server-database' }
                        // { text: 'app', handler:  function (btn) { this.up('apptoolbar').setCurrentDatabaseName(btn.text); } },
                        // { text: 'main', handler: function (btn) { this.up('apptoolbar').setCurrentDatabaseName(btn.text); } }
                      ]
                    },
                    {
                      text: 'List',
                      iconCls: 'icon-application-view-list',
                      handler: function (btn) { FrontSuite.app.addTab('auth.db'); },
                      tooltip: { text: 'Show all currently defined databases' }
                    },
                    {
                      text: 'Create New',
                      iconCls: 'icon-server-add',
                      tooltip: { text: 'Create a new database using one of the enabled database storage engines. You will be able to extract data out of other viewable databases, put it in the new one, and perform local analysis on it.' },
                      handler: function (btn) {
                          if (!toolbar.newDatabaseDialog) {
                              var panel = Ext.create('FrontSuite.view.DatabasePanel', {id: 'newdb-form-panel', create: 1 });
                              toolbar.newDatabaseDialog = FrontSuite.app.createModalDialog({id: 'newdb-dialog', title: 'Create Database', panel: panel});
                          }
                          toolbar.newDatabaseDialog.show();
                      }
                    },
                    {
                      text: 'Refresh',
                      iconCls: 'icon-database-refresh',
                      handler: function (btn) {
                          if (!toolbar.db_name) {
                              FrontSuite.app.error({message: 'You must choose a current database first before you attempt to refresh it'});
                          }
                          else {
                              FrontSuite.server.Database.refreshDatabaseInformation(toolbar.db_name, function (response, callinfo) {
                                  if (response && response.success == true) {
                                      FrontSuite.app.message('Status','Database refresh ('+toolbar.db_name+') complete');
                                  }
                                  else {
                                      FrontSuite.app.error({message: callinfo.message});
                                  }
                              });
                          }
                      },
                      tooltip: { text: 'Refresh the information we keep about the selected database.' }
                    },
                    {
                      text: 'Advanced',
                      iconCls: 'icon-database-gear',
                      menu: [
                        {
                          text: 'Backup',
                          iconCls: 'icon-database-save',
                          handler: function (btn) { FrontSuite.app.notify(btn.text); },
                          tooltip: { text: 'Backup the entire database to a file which can be downloaded.' }
                        },
                        {
                          text: 'Restore',
                          iconCls: 'icon-database-save',
                          handler: function (btn) { FrontSuite.app.notify(btn.text); },
                          tooltip: { text: 'Restore the entire database from a previously created backup file.' }
                        },
                        {
                          text: 'Drop',
                          iconCls: 'icon-server-delete',
                          handler: function (btn) { FrontSuite.app.notify(btn.text); },
                          tooltip: { text: 'CAUTION!!! Drop (destroy, delete) the entire database.' }
                        }
                      ]
                    }
                ]
            },
            '-',
            {
                id:   'app-toolbar-table',
                text: 'Table',
                iconCls: 'icon-database-table',
                menu: [
                    {
                      id:   'app-toolbar-table-select',
                      text: 'Choose Table',
                      iconCls: 'icon-table-go',
                      menu: [
                        { text: '(none)', iconCls: 'icon-table-error' }
                        // { text: 'db', handler: function (btn) { this.up('apptoolbar').setCurrentTableName(btn.text); } },
                        // { text: 'db_table_01', handler: function (btn) { this.up('apptoolbar').setCurrentTableName(btn.text); } },
                      ]
                    },
                    {
                      text: 'List',
                      iconCls: 'icon-application-view-list',
                      handler: function (btn) { FrontSuite.app.addTab('meta.db_table'); },
                      tooltip: { text: 'Show all currently defined database tables' }
                    },
                    {
                      text: 'Create New',
                      iconCls: 'icon-table-add',
                      tooltip: { text: 'Create a new table on the currently selected database. You will be able to put rows of data into your tables.' },
                      handler: function (btn) {
                          if (!toolbar.newDatabaseTableDialog) {
                              var panel = Ext.create('FrontSuite.view.DatabaseTablePanel', {id: 'newdbtable-form-panel', create: 1, databaseName: toolbar.db_name });
                              toolbar.newDatabaseTableDialog = FrontSuite.app.createModalDialog({id: 'newdbtable-dialog', title: 'Create Database Table', panel: panel});
                          }
                          toolbar.newDatabaseTableDialog.show();
                      }
                    },
                    {
                      text: 'Refresh',
                      iconCls: 'icon-table-refresh',
                      handler: function (btn) {
                          if (!toolbar.db_name || !toolbar.table_name) {
                              FrontSuite.app.error({message: 'You must choose a current database and table first before you attempt to refresh the table'});
                          }
                          else {
                              FrontSuite.server.Database.refreshDatabaseInformation(toolbar.db_name, toolbar.table_name, function (response, callinfo) {
                                  if (response && response.success == true) {
                                      FrontSuite.app.message('Status','Database table refresh ('+toolbar.db_name+'.'+toolbar.table_name+') complete');
                                  }
                                  else {
                                      FrontSuite.app.error({message: callinfo.message});
                                  }
                              });
                          }
                      },
                      tooltip: { text: 'Refresh the information we keep about the selected table in the selected database.' }
                    },
                    { text: 'Export/Download', iconCls: 'icon-table-save', handler: function (btn) { FrontSuite.app.notify(btn.text); } },
                    {
                      text: 'Advanced',
                      iconCls: 'icon-table-gear',
                      menu: [
                        { text: 'Upload/Replace', iconCls: 'icon-table-save',   handler: function (btn) { FrontSuite.app.notify(btn.text); } },
                        { text: 'Backup',         iconCls: 'icon-table-save',   handler: function (btn) { FrontSuite.app.notify(btn.text); } },
                        { text: 'Restore',        iconCls: 'icon-table-save',   handler: function (btn) { FrontSuite.app.notify(btn.text); } },
                        { text: 'Drop',           iconCls: 'icon-table-delete', handler: function (btn) { FrontSuite.app.notify(btn.text); } }
                      ]
                    }
                ]
            },
            '-',
            //{
            //    text: 'Remote Sync',
            //    iconCls: 'icon-arrow-refresh',
            //    menu: [
            //        { text: 'DBFoundry Account Setup',
            //          iconCls: 'icon-user',
            //          handler: function (btn) { FrontSuite.app.notify(btn.text); }
            //        },
            //        { text: 'DBFoundry Sync',
            //          iconCls: 'icon-arrow-refresh-small',
            //          handler: function (btn) { FrontSuite.app.notify(btn.text); }
            //        }
            //    ]
            //},
            //'-',
            '->',
            '-',
            {
                id: 'app-toolbar-user',
                xtype: 'button',
                iconCls: 'icon-user',
                text: userButtonText,
                menu: [
                    {
                        id: 'app-toolbar-user-login',
                        iconCls: 'icon-status-online',
                        hidden: loggedIn,
                        text: 'Login',
                        handler: function (btn) { toolbar.showUserDialog('login', function () { toolbar.setupApplicationAfterLogin(); }); }
                    },
                    {
                        id: 'app-toolbar-user-logout',
                        iconCls: 'icon-status-busy',
                        hidden: !loggedIn,
                        text: 'Logout',
                        handler: function (btn) {
                            var old_user_token = FrontSuite.session.user_token;
                            FrontSuite.util.ext.logout(function () {
                                toolbar.setupApplicationAfterLogout(old_user_token);
                            });
                        }
                    },
                    '-',
                    {
                        id: 'app-toolbar-user-register',
                        iconCls: 'icon-user-add',
                        hidden: loggedIn,
                        text: 'Register',
                        handler: function (btn) { toolbar.showUserDialog('register'); }
                    },
                    {
                        id: 'app-toolbar-user-profile',
                        iconCls: 'icon-user-edit',
                        hidden: !loggedIn,
                        text: 'Profile',
                        handler: function (btn) { toolbar.showUserDialog('profile'); }
                    }
                    //{
                    //    id: 'app-toolbar-user-list',
                    //    hidden: !loggedIn,
                    //    text: 'List',
                    //    handler: function (btn) { FrontSuite.app.addTab('auth.auth_user'); }
                    //},
                    //{
                    //    id: 'app-toolbar-user-chgpass',
                    //    hidden: !loggedIn,
                    //    text: 'Change Password',
                    //    handler: function (btn) { toolbar.showUserDialog('passchg'); }
                    //}
                ]
            },
            {
                id: 'app-toolbar-group',
                xtype: 'button',
                iconCls: 'icon-group',
                text: groupButtonText,
                menu: [
                    {
                        id: 'app-toolbar-group-select',
                        iconCls: 'icon-group-go',
                        text: 'Choose Group',
                        menu: groupMenu
                    }
                    //'-',
                    //{
                    //    id: 'app-toolbar-group-create',
                    //    iconCls: 'icon-group-add',
                    //    hidden: !loggedIn,
                    //    text: 'Create Group'
                    //},
                    //{
                    //    id: 'app-toolbar-group-list',
                    //    hidden: !loggedIn,
                    //    text: 'List Groups'
                    //},
                    //{
                    //    id: 'app-toolbar-group-members',
                    //    hidden: !loggedIn,
                    //    text: 'List Members'
                    //},
                    //{
                    //    id: 'app-toolbar-group-request',
                    //    hidden: !loggedIn,
                    //    text: 'Request Membership'
                    //},
                    //{
                    //    id: 'app-toolbar-group-invite',
                    //    hidden: !loggedIn,
                    //    text: 'Invite Members'
                    //},
                    //{
                    //    id: 'app-toolbar-group-delete',
                    //    iconCls: 'icon-group-delete',
                    //    hidden: !loggedIn,
                    //    text: 'Delete Group'
                    //}
                ]
            },
            {
                id: 'app-toolbar-app',
                xtype: 'button',
                iconCls: 'icon-application-side-tree',
                text: appButtonText,
                menu: [
                    {
                        id: 'app-toolbar-app-select',
                        text: 'Choose Application',
                        iconCls: 'icon-application-go',
                        menu: appMenu
                    }
                ]
            },
            '-',
            //{
            //    text: 'Usage',
            //    handler: function(btn) {
            //        if (!this.usageDialog) {
            //            var panel  = Ext.create('FrontSuite.view.UsageDialog');
            //            this.usageDialog = FrontSuite.app.createModalDialog({id: 'usage-dialog', title: 'Account Usage', panel: panel});
            //        }
            //        this.usageDialog.show();
            //    }
            //},
            //'-',
            {
                text: 'Feedback',
                iconCls: 'icon-email',
                menu: [
                    { text: 'Contact Us',               iconCls: 'icon-email',       handler: function (btn) { FrontSuite.app.notify(btn.text); } },
                    { text: 'Submit a Bug Report',      iconCls: 'icon-email-error', handler: function (btn) { FrontSuite.app.notify(btn.text); } },
                    { text: 'Submit a Feature Request', iconCls: 'icon-email-add',   handler: function (btn) { FrontSuite.app.notify(btn.text); } }
                ]
            },
            '-',
            {
                xtype: 'button',
                text: 'Help',
                iconCls: 'icon-help',
                menu: [
                    { text: 'Welcome', iconCls: 'icon-page', handler: function (btn) { FrontSuite.app.addTab('welcome.html'); } }
                ]
            }
        ];

        this.newDatabaseObjectSelected();

        this.superclass.constructor.call(this, this.id);
        this.reflectLoggedInStateInToolbar();
        return(this);
    },

    isLoggedIn: function () {
        var loggedIn = (FrontSuite.session.user_token && FrontSuite.session.user_token != 'guest') ? true : false;
        return(loggedIn);
    },

    //value_labels: { 1:  '1 hour',   2:  '2 hours',  3:  '3 hours',  4:  '4 hours',  5:  '5 hours',  6:  '6 hours',
    //                9: '9 hours',  12: '12 hours', 15: '15 hours', 18: '18 hours', 21: '21 hours', 24: '24 hours'}

    showUserDialog: function (purpose, callback) {
        var key = purpose + 'Dialog';
        if (!this[key]) this[key] = Ext.create("FrontSuite.view.UserDialog", null, purpose, callback);
        this[key].show();
        // Ext.getCmp(this[key].id + '-user_token').focus();   // I can't seem to make this work in a short amount of time. moving on...
    },

    getCurrentDatabaseName: function () { return(this.db_name); },
    getCurrentTableName:    function () { return(this.table_name); },

    setCurrentDatabaseName: function (databaseName) {
        if (this.db_name != databaseName) {
            this.db_name = databaseName;
            var text = this.db_name ? ('Database ('+this.db_name+')') : 'Database';
            Ext.getCmp('app-toolbar-database-button').setText(text);
        }
    },

    setCurrentTableName: function (tableName) {
        if (this.table_name != tableName) {
            this.table_name = tableName;
            var text = this.table_name ? ('Table ('+this.table_name+')') : 'Table';
            Ext.getCmp('app-toolbar-table-button').setText(text);
        }
    },

    newGroup: function (groupname) {
        var toolbar = this;
        var groups, i;
        var group_id = 1;
        var app_id   = FrontSuite.session.app_id || 1;
        if (FrontSuite.session.user_token && FrontSuite.session.authdata && FrontSuite.session.authdata.groups) {
            groups = FrontSuite.session.authdata.groups;
            for (i = 0; i < groups.length; i++) {
                if (groups[i].group_name == groupname) {
                    group_id = groups[i].group_id;
                    break;
                }
            }
        }
        FrontSuite.util.ext.changeGroupOrApp(group_id, app_id, function (success, msg) {
            if (success == false) {
                FrontSuite.app.error({message: msg});
            }
            toolbar.reflectLoggedInStateInToolbar();
        });
    },

    newApp: function (app_cd) {
        var toolbar = this;
        var apps, i;
        var group_id = FrontSuite.session.group_id || 1;
        var app_id   = FrontSuite.session.app_id || 1;
        if (FrontSuite.session.user_token && FrontSuite.session.authdata && FrontSuite.session.authdata.apps) {
            apps = FrontSuite.session.authdata.apps;
            if (apps.length >= 1) {
                for (i = 0; i < apps.length; i++) {
                    if (apps[i].app_cd == app_cd) {
                        app_id = apps[i].app_id;
                        break;
                    }
                }
            }
        }
        FrontSuite.util.ext.changeGroupOrApp(group_id, app_id, function (success, msg) {
            if (success == false) {
                FrontSuite.app.error({message: msg});
            }
            toolbar.reflectLoggedInStateInToolbar();
        });
    },

    setupApplicationAfterLogin: function () {
        var toolbar = this;
        var user_token = FrontSuite.session.user_token;
        this.reflectLoggedInStateInToolbar();
        this.newDatabaseObjectSelected();
        Ext.getCmp('accordion-nav-panel').refresh();
        FrontSuite.app.message('Welcome', 'Welcome '+user_token);
    },

    setupApplicationAfterLogout: function (old_user_token) {
        var toolbar = this;
        this.reflectLoggedInStateInToolbar();
        this.newDatabaseObjectSelected();
        Ext.getCmp('accordion-nav-panel').refresh();
        FrontSuite.app.message('Goodbye', 'Goodbye '+old_user_token);
    },

    reflectLoggedInStateInToolbar: function () {
//console.log('toolbar.reflectLoggedInStateInToolbar()');
//console.log(FrontSuite.session);
        var toolbar = (this.id == 'app-toolbar') ? this : Ext.getCmp('app-toolbar');
        var authdata = FrontSuite.session.authdata;
        var user_token = FrontSuite.session.user_token;
        var userButton = Ext.getCmp('app-toolbar-user');
        var currentUserButtonText = userButton.getText();
        var newUserButtonText = (user_token) ? 'User ('+user_token+')' : 'User (guest)';
        if (newUserButtonText != currentUserButtonText) {
            userButton.setText(newUserButtonText);
            if (user_token && user_token != 'guest') {
                var nick_name = authdata.user.nick_name || authdata.user.first_name || authdata.user.user_token;
                Ext.getCmp('app-toolbar-user-login').hide();
                Ext.getCmp('app-toolbar-user-register').hide();
                Ext.getCmp('app-toolbar-user-logout').show();
                Ext.getCmp('app-toolbar-user-profile').show();
                // Ext.getCmp('app-toolbar-user-list').show();
                // Ext.getCmp('app-toolbar-user-chgpass').show();
            }
            else {
                Ext.getCmp('app-toolbar-user-login').show();
                Ext.getCmp('app-toolbar-user-register').show();
                Ext.getCmp('app-toolbar-user-logout').hide();
                Ext.getCmp('app-toolbar-user-profile').hide();
                // Ext.getCmp('app-toolbar-user-list').hide();
                // Ext.getCmp('app-toolbar-user-chgpass').hide();
            }
        }

        var groupButton = Ext.getCmp('app-toolbar-group');
        var groupSelectButton = Ext.getCmp('app-toolbar-group-select');
        var newGroupMenu = [];
        var i, newGroupButtonText;
        if (authdata.groups) {   // i.e. logged in
            var group_id  = FrontSuite.session.group_id;
            var groups   = authdata.groups;
            var groupname = 'all-users';
            for (i = 0; i < groups.length; i++) {
                newGroupMenu[i] = { text: groups[i].group_name, iconCls: 'icon-group', handler: function (btn, event) { toolbar.newGroup(btn.text); } };
                if (groups[i].group_id == group_id) groupname = groups[i].group_name;
            }
            newGroupButtonText = 'Group ('+groupname+')';
        }
        else {   // i.e. something went wrong
            newGroupMenu[0] = { text: 'all-users', iconCls: 'icon-group', handler: function (btn, event) { toolbar.newGroup(btn.text); } };
            newGroupButtonText = 'Group (all-users)';
        }
        groupButton.setText(newGroupButtonText);
        groupSelectButton.menu.removeAll();
        groupSelectButton.menu.add(newGroupMenu);

        var appButton = Ext.getCmp('app-toolbar-app');
        var appSelectButton = Ext.getCmp('app-toolbar-app-select');
        var newAppMenu = [];
        var i, newAppButtonText;
        if (authdata.apps) {
            var app_id  = FrontSuite.session.app_id;
            var apps   = authdata.apps;
            var app_cd = 'none';
            for (i = 0; i < apps.length; i++) {
                newAppMenu[i] = { text: apps[i].app_cd, iconCls: 'icon-application-side-tree', handler: function (btn, event) { toolbar.newApp(btn.text); } };
                if (apps[i].app_id == app_id) app_cd = apps[i].app_cd;
            }
            newAppButtonText = 'Application ('+app_cd+')';
        }
        else {   // i.e. something went wrong
            newAppMenu[0] = { text: 'none', iconCls: 'icon-application-side-tree', handler: function (btn, event) { toolbar.newApp(btn.text); } };
            newAppButtonText = 'Application (none)';
        }
        appButton.setText(newAppButtonText);
        appSelectButton.menu.removeAll();
        appSelectButton.menu.add(newAppMenu);
    },

    newDatabaseObjectSelected: function (nameOfValue, value) {
        if (nameOfValue) {
            if (nameOfValue == 'Database') {
                this.db_name = value;
            }
            else if (nameOfValue == 'Table') {
                this.table_name = value;
            }
        }
        FrontSuite.util.ext.listDatabaseObjects(this.db_name, this.table_name, function (response, message) {
            // console.log('listDatabaseObjects');
            // console.log(response);
            // console.log(callinfo);
            var toolbar = (this.id == 'app-toolbar') ? this : Ext.getCmp('app-toolbar');
            if (response && response.success == true) {

                toolbar.db_name = response.db_name;
                toolbar.updateDatabaseMenuButton(Ext.getCmp('app-toolbar-database'),
                                                 Ext.getCmp('app-toolbar-database-select'),
                                                 'icon-server-database', 'Database', 'db_name', response.db_name, response.databases);

                toolbar.table_name = response.table_name;
                toolbar.updateDatabaseMenuButton(Ext.getCmp('app-toolbar-table'),
                                                 Ext.getCmp('app-toolbar-table-select'),
                                                 'icon-table', 'Table', 'table_name', response.table_name, response.tables);
            }
            else {
                FrontSuite.app.error({message: message});
            }
        });
    },

    updateDatabaseMenuButton: function (menuButton, selectButton, iconClass, nameOfValue, columnName, currentValue, listOfObjects) {
        var toolbar = this;
        var newMenu = [];
        var i, newButtonText, value;

        if (currentValue) newButtonText = nameOfValue+' ('+currentValue+')';
        else              newButtonText = nameOfValue;

        if (listOfObjects && listOfObjects.length > 0) {
            for (i = 0; i < listOfObjects.length; i++) {
                value = listOfObjects[i][columnName];
                newMenu[i] = { text: value, iconCls: iconClass, handler: function (btn, event) { toolbar.newDatabaseObjectSelected(nameOfValue, btn.text); } };
            }
        }
        else {   // i.e. something went wrong
            newMenu[0] = { text: '(none)', iconCls: iconClass };
        }

        menuButton.setText(newButtonText);
        selectButton.menu.removeAll();
        selectButton.menu.add(newMenu);
    }
});

